<template>
    <div class="search">
        <Row :gutter="16" class="all-height">
            <Col :span="showRight ? 18 : 24" class="all-height">
                <Card class="all-height card-child-height">
                    <Row class="operation">
                        <Col span="22">
                            <Button v-has="'add'" @click="add" type="primary" icon="md-add">添加</Button>
                            <Button v-has="'delete'" @click="delAll" icon="md-trash">批量删除</Button>
                            <Button v-has="'input'" @click="dropImportData" type="primary">导入数据</Button>
                            <Button @click="getDataList" icon="md-refresh">刷新</Button>
                            <Button type="dashed" @click="openTip = !openTip">{{ openTip ? '关闭提示' : '开启提示' }}</Button>
                        </Col>
                        <Col span="2" style="text-align: right">
                            <Icon
                                color="#fff"
                                class="icon01"
                                :type="showRight ? `ios-arrow-forward` : `ios-arrow-back`"
                                @click.native="clickShowRight"
                            ></Icon>
                            <!--              <Button-->
                            <!--                  :icon="showRight?`ios-arrow-forward`:`ios-arrow-back`"-->
                            <!--                  @click.native="clickShowRight"-->
                            <!--                  size="mini"-->
                            <!--                  type="primary">-->
                            <!--              </Button>-->
                        </Col>
                    </Row>
                    <Row v-show="openTip">
                        <Alert show-icon>
                            已选择
                            <span class="select-count">{{ selectList.length }}</span>
                            项
                            <a class="select-clear" @click="clearSelectAll">清空</a>
                        </Alert>
                    </Row>
                    <Row class="calc-px-height">
                        <!-- <table
                :height="height1"
                :loading="loading"
                border
                :columns="columns"
                :data="data"
                ref="table"
                sortable="custom"
                @on-sort-change="changeSort"
                @on-selection-change="changeSelect"
                @on-row-dblclick="sjclaib"
            ></table> -->
                        <Table
                            :height="height1"
                            :loading="loading"
                            border
                            :columns="columns"
                            :data="data"
                            ref="table"
                            sortable="custom"
                            @on-sort-change="changeSort"
                            @on-selection-change="changeSelect"
                            @on-row-dblclick="sjclaib"
                        ></Table>
                    </Row>
                    <Row type="flex" justify="end" class="page">
                        <Page
                            :current="searchForm.pageNumber"
                            :total="total"
                            :page-size="searchForm.pageSize"
                            @on-change="changePage"
                            @on-page-size-change="changePageSize"
                            :page-size-opts="[10, 20, 50, 100, 200]"
                            size="small"
                            show-total
                            show-elevator
                            show-sizer
                        ></Page>
                    </Row>
                    <Drawer title="导入数据" closable v-model="importModalVisible" class="c-drawer02">
                        <div style="display: flex; justify-content: space-between; align-items: center">
                            <Upload action :before-upload="beforeUploadImport" accept=".xls, .xlsx">
                                <Button :loading="reading" icon="ios-cloud-upload-outline" class="cmr10">上传Excel文件</Button>
                                <span v-if="uploadfile.name">当前选择文件：{{ uploadfile.name }}</span>
                            </Upload>
                            <Button @click="clearImportData" icon="md-trash">清空数据</Button>
                        </div>
                        <Alert type="warning" show-icon>导入前请下载查看导入模版数据文件查看所需字段及说明，确保数据格式正确，不得修改列英文名称</Alert>
                        <Table :columns="importColumns" border :height="height" :data="importTableData" ref="importTable"></Table>
                        <div class="drawer-footer">
                            <Button @click="downloadTemple" type="info">下载导入模板</Button>
                            <div class="wrapper01" >
                                <Button @click="importModalVisible = false">关闭</Button>
                                <Button :loading="importLoading" :disabled="importTableData.length <= 0" @click="importData" class="cml8"  type="primary">
                                    确认导入
                                    <span v-if="importTableData.length > 0">{{ importTableData.length }} 条数据</span>
                                </Button>
                            </div>
                        </div>
                    </Drawer>

                    <!-- <addEdit :data="form" :type="showType" v-model="showDrawer" @on-submit="getDataList" /> -->
                </Card>
            </Col>
            <Col span="6" class="all-height" v-if="showRight">
                <Card class="all-height card-child-height">
                    <Row v-show="!showDrawer" @keydown.enter.native="handleSearch" >
                        <Col span="24">
                            <div class="drawer-header">
                                <div class="cmr16">查询区</div>
                            </div>
                        </Col>
                        <Col span="24">
                            <Form ref="searchForm" :model="searchForm"  :label-width="labelWidth70">
                                <FormItem label="外文名称" prop="foreignName">
                                    <Input type="text" v-model="searchForm.foreignName" placeholder="请输入外文名称" clearable style="width: 200px" />
                                </FormItem>
                                <FormItem label="中文名称" prop="chineseName">
                                    <Input type="text" v-model="searchForm.chineseName" placeholder="请输入中文名称" clearable style="width: 200px" />
                                </FormItem>
                                <FormItem label="所在国家或地区" prop="gjOrDq">
                                    <Input type="text" v-model="searchForm.gjOrDq" placeholder="请输入所在国家或地区" clearable style="width: 200px" />
                                </FormItem>
                                <FormItem  class="br " v-show="type != '0'">
                                    <Button @click="handleSearch" type="primary" icon="ios-search">搜索</Button>
                                    <Button @click="handleReset">重置</Button>
                                    <!--                <a class="drop-down" @click="dropDown">-->
                                    <!--                  {{ dropDownContent }}-->
                                    <!--                  <Icon :type="dropDownIcon"></Icon>-->
                                    <!--                </a>-->
                                </FormItem>
                                <!-- <FormItem style="margin-left:-35px;" class="br"> -->
                                <!-- <Button @click="handleSearch" type="primary" icon="ios-search">搜索</Button> -->
                                <!-- <Button @click="handleReset">重置</Button> -->
                                <!--                <a class="drop-down" @click="dropDown">-->
                                <!--                  {{ dropDownContent }}-->
                                <!--                  <Icon :type="dropDownIcon"></Icon>-->
                                <!--                </a>-->
                                <!-- </FormItem> -->
                            </Form>
                        </Col>
                        <!-- <div class="drawer-footer br" v-show="type != '0'">
                            <Button @click="handleSearch" type="primary" icon="ios-search">搜索</Button>
                            <Button @click="handleReset">重置</Button>
                        </div> -->
                    </Row>
                    <Row  v-show="showDrawer" >
                        <Col span="24">
                            <div class="drawer-header">
                                <div class="cmr16" v-show="showType != '2'">编辑区</div>
                                <div class="cmr16" v-show="showType == '2'">添加区</div>
                            </div>
                        </Col>
                        <Col span="24">
                            <Form ref="searchForm" :model="searchForm" :label-width="labelWidth70">
                                <FormItem label="外文名称" prop="foreignName">
                                    <Input v-model="form.foreignName" clearable />
                                </FormItem>
                                <FormItem label="中文名称" prop="chineseName">
                                    <Input v-model="form.chineseName" clearable />
                                </FormItem>
                                <FormItem label="所在国家或地区" prop="gjOrDq">
                                    <Input v-model="form.gjOrDq" clearable />
                                </FormItem>
                            </Form>
                        </Col>
                        <div class="drawer-footer br" v-show="type != '0'">
                            <Button type="primary" :loading="submitLoading" @click="handleSubmit">提交</Button>
                            <Button @click="showDrawer = false">取消</Button>
                        </div>
                    </Row>
                </Card>
            </Col>
        </Row>
    </div>
</template>

<script>
// 根据你的实际请求api.js位置路径修改
import { importGwschoolCode, getGwschoolCodeList, deleteGwschoolCode } from '@/api/gwschoolCode.js';
// 根据你的实际添加编辑组件位置路径修改
import addEdit from './addEdit.vue';
import { shortcuts } from '@/libs/shortcuts';
// import {importProvinceData} from "@/api";
import excel from '@/libs/excel';
import dict from '@/views/my-components/xboot/dict.vue';
import { addGwschoolCode, editGwschoolCode } from '@/api/gwschoolCode.js';
export default {
    name: 'gwschoolCode',
    components: {
        dict,
        addEdit
    },
    data() {
        return {
            labelWidth70: 90,
            openTip: true, // 显示提示
            showType: '0', // 添加或编辑标识
            showDrawer: false, // 显示添加编辑抽屉
            loading: true, // 表单加载状态
            height1: 0,
            searchForm: {
                // 搜索框初始化对象
                pageNumber: 1, // 当前页数
                pageSize: 50, // 页面大小
                sort: 'createTime', // 默认排序字段
                order: 'desc' // 默认排序方式
            },
            selectList: [], // 多选数据
            form: {
                // 添加或编辑表单对象初始化数据
                foreignName: '',
                chineseName: '',
                gjOrDq: '',
                sortOrder: 0
            },
            // 表单验证规则
            formValidate: {
                foreignName: [{ required: true, message: '不能为空', trigger: 'change' }],
                chineseName: [{ required: true, message: '不能为空', trigger: 'change' }],
                gjOrDq: [{ required: true, message: '不能为空', trigger: 'change' }]
                // sortOrder: [{ type: "number", required: true, message: "不能为空", trigger: "change" }],
            },
            columns: [],
            columns_1: Object.freeze([
                // 表头
                {
                    type: 'selection',
                    width: 60,
                    align: 'center'
                },
                {
                    type: 'index',
                    width: 60,
                    align: 'center'
                },
                {
                    title: '外文名称',
                    key: 'foreignName',
                    minWidth: 120,
                    sortable: false
                },
                {
                    title: '中文名称',
                    key: 'chineseName',
                    minWidth: 120,
                    sortable: false
                },
                {
                    title: '所在国家或地区',
                    key: 'gjOrDq',
                    minWidth: 120,
                    sortable: false
                },
                // {
                //   title: "排序值",
                //   key: "sortOrder",
                //   minWidth: 120,
                //   sortable: false,
                // },
                {
                    title: '操作',
                    key: 'action',
                    align: 'center',
                    width: 150,
                    render: (h, params) => {
                        return h('div', [
                            h(
                                'a',
                                {
                                    on: {
                                        click: () => {
                                            this.edit(params.row);
                                        }
                                    }
                                },
                                '编辑'
                            ),
                            h('Divider', {
                                props: {
                                    type: 'vertical'
                                }
                            }),
                            h(
                                'a',
                                {
                                    on: {
                                        click: () => {
                                            this.remove(params.row);
                                        }
                                    }
                                },
                                '删除'
                            )
                        ]);
                    }
                }
            ]),
            data: [], // 表单数据
            reading: false,
            importLoading: false,
            importTableData: [],
            pageNumber: 1, // 当前页数
            importModalVisible: false,
            importColumns: [],
            uploadfile: {
                name: ''
            },
            pageSize: 50, // 页面大小
            total: 0, // 表单数据总数
            showRight: true,
            submitLoading: false
        };
    },
    methods: {
        tableheig() {
            var bbb = document.getElementsByClassName('calc-px-height')[0].scrollHeight;
            var aaa = document.getElementsByClassName('calc-px-height')[0].children[0].children[0].children[1];
            var ccc = document.getElementsByClassName('calc-px-height')[0].children[0].children[0].children[0].scrollHeight;
            var ddd = bbb - ccc;
            console.log(bbb, '00000000000000');
            aaa.style.height = `${ddd}px`;

            if (this.searchForm.pageSize === 10) {
                this.height1 = 0;
            } else {
                this.height1 = document.getElementsByClassName('calc-px-height')[0].scrollHeight;
                if (this.total < this.searchForm.pageNumber * this.searchForm.pageSize) {
                    var r = (this.searchForm.pageNumber - 1) * this.searchForm.pageSize;
                    var a = this.total - r;
                    var s = a * 43 + 65;
                    if (s < this.height1) {
                        this.height1 = 0;
                    }
                }
            }
            if (this.total < 10) {
                this.height1 = 0;
            }
        },
        handleSearch() {
            this.searchForm.pageNumber = 1;
            this.searchForm.pageSize = 50;
            this.getDataList();
        },
        handleReset() {
            this.$refs.searchForm.resetFields();
            this.searchForm.pageNumber = 1;
            this.searchForm.pageSize = 50;
            // 重新加载数据
            this.getDataList();
        },
        clickShowRight() {
            this.showRight = !this.showRight;
        },
        dropImportData() {
            this.importModalVisible = true;
        },
        beforeUploadImport(file) {
            this.uploadfile = file;
            const fileExt = file.name.split('.').pop().toLocaleLowerCase();
            if (fileExt == 'xlsx' || fileExt == 'xls') {
                this.readFile(file);
                this.file = file;
            } else {
                this.$Notice.warning({
                    title: '文件类型错误',
                    desc: '所选文件‘ ' + file.name + ' ’不是EXCEL文件，请选择后缀为.xlsx或者.xls的EXCEL文件。'
                });
            }
            return false;
        },
        readFile(file) {
            this.reading = true;
            const reader = new FileReader();
            reader.readAsArrayBuffer(file);
            reader.onerror = e => {
                this.reading = false;
                // this.$Message.error("文件读取出错");
                this.$Message.error({
                    content: '文件读取出错',
                    duration: 5,
                    closable: true
                });
            };
            reader.onload = e => {
                const data = e.target.result;
                const { header, results } = excel.read(data, 'array');
                const tableTitle = header.map(item => {
                    return { title: item, key: item, minWidth: 130, align: 'center' };
                });
                this.importTableData = results;
                this.importColumns = tableTitle;
                this.reading = false;
                this.$Message.success('读取数据成功');
            };
        },
        downloadTemple() {
            window.location.href = process.env.BASE_URL + '留学院校导入模板.xlsx';
        },
        importData() {
            let params = this.importTableData.map(item => {
                return {
                    foreignName: item['外文名称'],
                    chineseName: item['中文名称'],
                    gjOrDq: item['所在国家或地区']
                    // sortorder:item["排序值"]
                };
            });
            this.importLoading = true;
            importGwschoolCode(params).then(res => {
                this.importLoading = false;
                if (res.success) {
                    this.importModalVisible = false;
                    this.getDataList();
                    this.$Modal.info({
                        title: '导入结果',
                        content: res.message
                    });
                }
            });
        },
        clearImportData() {
            this.importTableData = [];
            this.importColumns = [];
            this.uploadfile = {};
        },
        init() {
            this.getDataList();
        },
        changePage(v) {
            this.searchForm.pageNumber = v;
            this.getDataList();
            this.clearSelectAll();
        },
        changePageSize(v) {
            this.searchForm.pageSize = v;
            this.getDataList();
        },
        changeSort(e) {
            this.searchForm.sort = e.key;
            this.searchForm.order = e.order;
            if (e.order === 'normal') {
                this.searchForm.order = '';
            }
            this.getDataList();
        },
        clearSelectAll() {
            this.$refs.table.selectAll(false);
        },
        changeSelect(e) {
            this.selectList = e;
        },
        getDataList() {
            this.loading = true;
            getGwschoolCodeList(this.searchForm).then(res => {
                this.loading = false;
                console.log(res.result.records, 'res.result.records');
                if (res.success) {
                    this.data = res.result.records;
                    this.total = res.result.total;
                    this.tableheig();
                    if (this.data.length == 0 && this.searchForm.pageNumber > 1) {
                        this.searchForm.pageNumber -= 1;
                        this.getDataList();
                    }
                }
            });
        },
        add() {
            this.showType = '2';
            this.form = {};
            this.showDrawer = true;
        },
        // 双击表格行
        sjclaib(v) {
            for (let attr in v) {
                if (v[attr] == null) {
                    v[attr] = '';
                }
            }
            let str = JSON.stringify(v);
            let data = JSON.parse(str);
            this.form = data;
            this.showType = '1';
            this.showDrawer = true;
        },
        edit(v) {
            // 转换null为""
            for (let attr in v) {
                if (v[attr] == null) {
                    v[attr] = '';
                }
            }
            let str = JSON.stringify(v);
            let data = JSON.parse(str);
            this.form = data;
            this.showType = '1';
            this.showDrawer = true;
        },
        handleSubmit() {
            this.$refs.searchForm.validate(valid => {
                if (valid) {
                    if (this.showType == '1') {
                        // 编辑
                        this.submitLoading = true;
                        editGwschoolCode(this.form).then(res => {
                            this.submitLoading = false;
                            if (res.success) {
                                this.$Message.success('操作成功');
                                this.getDataList();
                                this.showDrawer = false;
                            }
                        });
                        console.log('454545454');
                    } else {
                        // 添加
                        this.submitLoading = true;
                        addGwschoolCode(this.form).then(res => {
                            this.submitLoading = false;
                            if (res.success) {
                                this.$Message.success('操作成功');
                                this.$emit('on-submit', true);
                                this.getDataList();
                                this.showDrawer = false;
                            }
                        });
                        console.log('454545454');
                    }
                }
            });
        },
        remove(v) {
            this.$Modal.confirm({
                title: '确认删除',
                // 记得确认修改此处
                content: '您确认要删除该条数据?',
                loading: true,
                onOk: () => {
                    // 删除
                    deleteGwschoolCode({ ids: v.id }).then(res => {
                        this.$Modal.remove();
                        if (res.success) {
                            this.$Message.success('操作成功');
                            this.clearSelectAll();
                            this.getDataList();
                        }
                    });
                }
            });
        },
        delAll() {
            if (this.selectList.length <= 0) {
                this.$Message.warning('您还未选择要删除的数据');
                return;
            }
            this.$Modal.confirm({
                title: '确认删除',
                content: '您确认要删除所选的 ' + this.selectList.length + ' 条数据?',
                loading: true,
                onOk: () => {
                    let ids = '';
                    this.selectList.forEach(function (e) {
                        ids += e.id + ',';
                    });
                    ids = ids.substring(0, ids.length - 1);
                    // 批量删除
                    deleteGwschoolCode({ ids: ids }).then(res => {
                        this.$Modal.remove();
                        if (res.success) {
                            this.$Message.success('操作成功');
                            this.clearSelectAll();
                            this.getDataList();
                        }
                    });
                }
            });
        },
        onRestWindow() {
            this.columns = this.restTableCellWidth(this.columns_1)
            this.labelWidth70 = this.searchLabelWidth(this.labelWidth70)
        }
    },
    mounted() {
        this.onRestWindow()
        window.addEventListener('resize',this.onRestWindow)
        this.init();
    },
    beforeDestroy() {
        window.removeEventListener('resize',this.onRestWindow)
    }
};
</script>
<style lang="less">
// 建议引入通用样式 具体路径自行修改 可删除下面样式代码
@import '../../../styles/table-common.less';
@import '../../personInfo.less';
.search {
    .operation {
        margin-bottom: 2vh;
    }
    .select-count {
        font-weight: 600;
        color: #40a9ff;
    }
    .select-clear {
        margin-left: 10px;
    }
    .page {
        margin-top: 2vh;
    }
    .drop-down {
        margin-left: 5px;
    }
}
</style>
<style lang="less" scoped>
.icon01 {
    background: rgb(45, 154, 244); border-radius: 50%; padding: 3px
}
.cmr16{
    margin-right: 16px
}
.cmr10 {
    margin-right: 10px 
}
.cml-35 {
    margin-left: -35px;
}
.c-drawer02 {
    /deep/ .ivu-drawer {
        width:1000px !important;
    }
    
}
.wrapper01 {
    position: absolute; right: 15px; display: inline-block
}
.wrapper03 {
    border-bottom: 1px solid #e9e9e9; padding-bottom: 6px; margin-bottom: 6px
}
.cml8{
    margin-left: 8px
}
</style>